import Conversition from "@/class/Conversition";
import {useMainStore} from "@/store/main";
import {notification, Button} from 'ant-design-vue';
import {h} from 'vue';
import {SlackSquareOutlined, MailOutlined} from '@ant-design/icons-vue';
import {notNotifyAgain} from '@/api/meeting'
import {countUnDoFriendApply, getChatFriendApplyList} from "@/api/chat";

const store = useMainStore()
const chatUrl: any = import.meta.env.VITE_WEBSOCKET_URL;

export function initChatSocket(userId) {
    const socket = new WebSocket(chatUrl + "/chatSocket/" + userId);
    store.setSocket(socket);
    socket.onopen = (event) => {
        console.log('WebSocket connection opened:', event);
    };

    socket.onmessage = async (event) => {
        const data = JSON.parse(event.data)
        //接收消息
        const reciverMsg = data["reciverMsg"]
        if (reciverMsg) {
            const reciverData = JSON.parse(reciverMsg)
            if (reciverData.reciverId == store.sender.id) {
                store.playMusic();
                if (window.Notification && Notification.permission !== "denied") {
                    if (reciverData.type == 5) {//添加好友的申请
                        notification.open({
                            message: '消息通知',
                            description: `${reciverData.content}`,
                            icon: () => h(MailOutlined, {style: 'color: #108ee9'}),
                        });
                        //重新计算好友申请数量和重新获取好友申请
                        const data: any = await countUnDoFriendApply()
                        store.unDoFriendApplyNumber = data.result > 999 ? "999+" : data.result;
                        getAllApply()
                    } else {
                        notification.open({
                            message: '消息通知',
                            description: `${reciverData.sendName}给您发了一条消息`,
                            icon: () => h(MailOutlined, {style: 'color: #108ee9'}),
                        });
                    }
                }
                for (let item of store.sessionList) {
                    let id = item?.fromId || item?.id;
                    if (store.navId == 1 && id == reciverData.sendId && store.sessionSelectId == reciverData.sendId) {
                        reciverData.readFlag = true;
                        let query = {
                            sendId: reciverData.sendId,
                            reciverId: store.sender.id,
                            type: "changeMsgRead"
                        };
                        if (store?.socket) {
                            store.socket?.send(JSON.stringify(query));
                            break;
                        }
                    }
                }
                store.sendLocal(reciverData);
                let len =
                    store.sessionList.filter((x: any) => {
                        let id = x?.fromId || x.id;
                        return id == reciverData.sendId;
                    })?.length ?? 0;
                if (len === 0) {
                    if (store.allSessionList?.length > 0) {
                        let item: any = store.allSessionList.find((x: any) => x.id == reciverData.sendId);
                        let session = {
                            fromId: item.id,
                            username: item.username,
                            realname: item.realname,
                            personalitySign: item.personalitySign,
                            mobile: item.mobile,
                            region: item.region,
                            avatar: item.avatar,
                            email: item.email,
                            ownerId: store.sender.id,
                        };
                        store.sessionList.push(session);
                    }
                }
                store.toBottom();
            }
        }

        //更新消息状态为发送成功
        const changMsgState = data["changMsgState"]
        if (changMsgState) {
            const msgStateData = JSON.parse(changMsgState)
            store.conversitionList.map((x: Conversition) => {
                if (x.noCode != null && x.noCode == msgStateData.noCode) {
                    x.state = 1;
                }
            });
        }

        //近期会议提醒通知
        const meetingNotifyData = data["recentMeetingNotify"]
        if (meetingNotifyData) {
            const key = `open${Date.now()}`;
            notification.open({
                message: '会议通知',
                description: meetingNotifyData.notifyContent,
                icon: () => h(SlackSquareOutlined, {style: 'color: #108ee9'}),
                btn: () =>
                    h(
                        Button,
                        {
                            type: 'primary',
                            size: 'small',
                            onClick: () => notNotify(meetingNotifyData.dataId, key),
                        },
                        {default: () => '不再提醒'},
                    ),
                key
            });
        }
    }

    socket.onclose = (event) => {
        console.log('WebSocket connection closed:', event);
    };
    socket.onerror = (event) => {
        console.log('WebSocket connection error:', event);
    };
}

//近期会议提醒通知-不再提醒
async function notNotify(id, key) {
    await notNotifyAgain(id)
    notification.close(key)
}

async function getAllApply() {
    store.allApplyList = []
    let query = {
        pageNo: 1,
        pageSize: 30,
    };
    const data: any = await getChatFriendApplyList(query)
    store.allApplyList.push(...data.result?.records);
}
